package com.app.micaihu.view.main.msgcenter;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.base.BaseListActivity;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.message.EditorRecommendBean;
import com.app.micaihu.bean.message.NewEditorRmdBean;
import com.app.micaihu.configure.ConfigKeyConstant;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.db.NewsDBSqlHelper;
import com.app.micaihu.db.NewsDBUtil;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.AppConfigManager;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.view.main.msgcenter.adapter.NewEditorRecommendAdapter;
import com.app.utils.pulltorefresh.LoadingLayoutProxy;
import com.app.utils.pulltorefresh.PullToRefreshBase;
import com.app.utils.util.ViewSizeUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Guo on 2016/10/14.
 * <p>
 * 小编推荐 页面
 */
public class EditorRecommendActivity extends BaseListActivity<NewEditorRmdBean> {


    @Override
    protected void changeView() {
        super.changeView();
        //setTitle("小编特荐");

        Intent intent = getIntent();
        if (intent != null) {
            String stringExtra = intent.getStringExtra(MsgCenterListActivity.TITLE_NAME);
            if (!TextUtils.isEmpty(stringExtra)) {
                setTitle(stringExtra);

            }
        }


        if (mListView != null) {
            mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
            mListView.getRefreshableView().setBackgroundResource(R.color.common_bg_color_4);
            mListView.setBackgroundResource(R.color.common_bg_color_4);

            ((LoadingLayoutProxy) (mListView.getLoadingLayoutProxy())).setOnlyImageVisiby();
            ((LoadingLayoutProxy) (mListView.getLoadingLayoutProxy())).setLoadingBackground(R.color.common_bg_color_4);
        }
    }

    @Override
    protected void changeData(final boolean isRefresh) {

        checkDeprecatedData();
        //拿取数据：
        Map<String, String> params = new HashMap<>();
        if (UserInforManager.getInstance().isLogin()) {
            params.put("uid", UserInforManager.getInstance().getUserInfor().getUid());
        }
        HttpListener<DataBean<List<NewEditorRmdBean>>> newEditorListener = new HttpListener<DataBean<List<NewEditorRmdBean>>>() {
            @Override
            public void onStart() {
                super.onStart();
                setLoadView(LOADING, null);
            }

            @Override
            public void onError(VolleyError error) {
                getLocalData(true, 4);
            }

            @Override
            public void onSuccess(DataBean<List<NewEditorRmdBean>> response) {
                if (response.noError()) {
                    List<NewEditorRmdBean> editorRmdBeanList = response.getData();
                    if (editorRmdBeanList != null && !editorRmdBeanList.isEmpty()) {
                        //将拿到的数据存储到本地中
                        newInsertLocal(editorRmdBeanList);
                        //拿取本地的数据
                        getLocalData(true, 4);
                    } else {
                        getLocalData(true, 4);
                    }
                }
            }
        };
        addPostRequest(URIContant.NEWS_NEW_RECOMMEND, new TypeToken<DataBean<List<NewEditorRmdBean>>>() {
        }.getType(), params, newEditorListener);

    }


    /**
     * 检查以前版本的数据。
     */
    private void checkDeprecatedData() {
        if (!AppConfigManager.getInstance().readConfig(ConfigKeyConstant.clear_editor_table, false)) {
            String sql = "delete from " + NewsDBSqlHelper.EDITOR_RECOMMEND + ";";
            NewsDBUtil.getInstance().changeData(sql);
            AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.clear_editor_table, true);
        }


    }

    private void insertLocal(List<EditorRecommendBean> editorRecommendList) {
        Gson gson = new Gson();
        for (int i = 0; i < editorRecommendList.size(); i++) {
            if (editorRecommendList.get(i) != null) {
                try {
                    boolean b = NewsDBUtil.getInstance().insertRecommend(editorRecommendList.get(i).getExactTime(), gson.toJson(editorRecommendList.get(i)), false);
                    if (!b) {
                        NewsDBUtil.getInstance().insertRecommend(editorRecommendList.get(i).getExactTime(), gson.toJson(editorRecommendList.get(i)), true);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 2.0.2版本 插入本地的方法
     *
     * @param newEditorRmdBeanList
     */
    private void newInsertLocal(List<NewEditorRmdBean> newEditorRmdBeanList) {
        Gson gson = new Gson();
        for (int i = 0; i < newEditorRmdBeanList.size(); i++) {
            if (newEditorRmdBeanList.get(i) != null) {
                try {
                    boolean b = NewsDBUtil.getInstance().insertRecommend(newEditorRmdBeanList.get(i).getExactTime(), gson.toJson(newEditorRmdBeanList.get(i)), false);
                    if (!b) {
                        NewsDBUtil.getInstance().insertRecommend(newEditorRmdBeanList.get(i).getExactTime(), gson.toJson(newEditorRmdBeanList.get(i)), true);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 拿取本地的历史数据
     */
    private List tempList;

    private void getLocalData(final boolean refresh, int limit) {
        if (dataList == null) {
            dataList = new ArrayList<NewEditorRmdBean>();
        }
        String localRecomendList = NewsDBUtil.getInstance().getLocalRecomendList(dataList.size(), limit);

        if (TextUtils.isEmpty(localRecomendList)) {
            if (dataList.isEmpty()) {
                setLoadView(DATAEMPTY, TypeConstant.EMPTYVIEW_DEFAULT, getString(R.string.msg_empty_recommend));
            } else {
                setLoadView(LOADSUCES, getString(R.string.msg_nomore_recommend));
            }
        } else {
            Gson gson = new Gson();
//            List<EditorRecommendBean> list;
            List<NewEditorRmdBean> list;
            try {
//                list = gson.fromJson(localRecomendList, new TypeToken<List<EditorRecommendBean>>() {
                list = gson.fromJson(localRecomendList, new TypeToken<List<NewEditorRmdBean>>() {
                }.getType());
                if (list != null && !list.isEmpty()) {
                    dataList.addAll(0, list);
                    this.tempList = list;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (dataList.isEmpty()) {
                setLoadView(DATAEMPTY, TypeConstant.EMPTYVIEW_DEFAULT, getString(R.string.msg_empty_recommend));
            } else {
                mListView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mAdapter == null) {
                            mAdapter = new NewEditorRecommendAdapter(dataList, EditorRecommendActivity.this);
                            mListView.setAdapter(mAdapter);
                        } else {
                            mAdapter.notifyDataSetChanged();
                        }
                        mListView.onRefreshComplete();
                        if (refresh) {
                            mListView.getRefreshableView().setSelectionFromTop(dataList.size(), ViewSizeUtils.dp2px(mActivity, 50));
                        } else {//滑动到当前的
                            mListView.getRefreshableView().setSelectionFromTop(tempList.size() + 1, ViewSizeUtils.dp2px(mActivity, 50));
                        }
                    }
                }, 500);
            }


        }

    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void setListViewOnLastItemVisibleListener() {
        super.setListViewOnLastItemVisibleListener();
        if (mListView != null) mListView.setOnLastItemVisibleListener(null);
    }


    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        getLocalData(false, 4);
    }
}
